package com.image.androidimagebroswer.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.image.androidimagebroswer.R;

import java.util.List;

/**
 * Created by liuzhao.futrue on 2018/8/26.
 */

public class GridListAdapter extends RecyclerView.Adapter<GridListAdapter.GridListAdapterHolder>
        implements View.OnClickListener {

    private Context mContext;
    private List<String> mPhotoList;// 图片地址集合
    private OnItemClickListener mListener;

    public GridListAdapter(Context context, List<String> list) {
        this.mContext = context;
        this.mPhotoList = list;
    }

    @NonNull
    @Override
    public GridListAdapterHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 创建ViewHolder
        View itemView = LayoutInflater.from(mContext).inflate(R.layout.item_grid, null);
        itemView.setOnClickListener(this);
        GridListAdapterHolder holder = new GridListAdapterHolder(itemView);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull GridListAdapterHolder holder, int position) {
        // ViewHolder 数据绑定
        holder.getView().setTag(position);// 将position绑定在holder.view中，然后在取的地方通过getTag来获取；
        Glide.with(mContext).load(mPhotoList.get(position)).into(holder.getImageView());
    }

    @Override
    public int getItemCount() {
        // 总共的条目数量
        return mPhotoList.size();
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mListener = listener;
    }

    /**
     * 此处的View就是Adapter的ItemView
     */
    @Override
    public void onClick(View v) {
        if (mListener != null) {
            mListener.onItemClick(v, (int) v.getTag());
        }
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    class GridListAdapterHolder extends RecyclerView.ViewHolder {
        private ImageView mImageView;
        private View mView;

        public GridListAdapterHolder(View itemView) {
            super(itemView);
            mView = itemView;
            mImageView = itemView.findViewById(R.id.iv_item_grid);
        }

        public ImageView getImageView() {
            return mImageView;
        }

        public View getView() {
            return mView;
        }

    }

}
